package com.xiaoye.qbproject.handler;

import com.alibaba.fastjson2.JSONArray;
import com.xiaoye.qbproject.domain.ZbAttr;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;

import java.io.StringReader;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author : ChenYao
 * @version : 1.0
 * @description :
 * @create : 2024-12-31 16:04
 */
@Component
@MappedTypes(ZbAttr.class)
public class ZbAttrCustomTypeHandler extends BaseTypeHandler<List<ZbAttr>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<ZbAttr> parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            ps.setNull(i, java.sql.Types.CLOB);
        } else {
            StringReader reader = new StringReader(JSONArray.toJSONString(parameter));
            ps.setClob(i, reader);
        }
    }

    @Override
    public List<ZbAttr> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 从ResultSet中获取数据库类型并转换为Java类型
        String json = rs.getString(columnName);
        if (json != null) {
            return JSONArray.parseArray(json, ZbAttr.class);
        }
        return null;
    }

    @Override
    public List<ZbAttr> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        // 从ResultSet中获取数据库类型并转换为Java类型
        String json = rs.getString(columnIndex);
        if (json != null) {
            return JSONArray.parseArray(json, ZbAttr.class);
        }
        return null;
    }

    @Override
    public List<ZbAttr> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        // 从CallableStatement中获取数据库类型并转换为Java类型
        String json = cs.getString(columnIndex);
        if (json != null) {
            return JSONArray.parseArray(json, ZbAttr.class);
        }
        return null;
    }
}
